import { IframeEnv } from "rollup-web";
import { RollupWebRuntime } from "../RollupWebRuntime";

export class LocalIframeRuntime extends RollupWebRuntime {
    iframe?: IframeEnv;
    public container: HTMLElement;
    init(config: { container: HTMLElement }): void {
        Object.assign(this, config);
    }
    async build() {
        const port = await this.Compiler.createPort(); // 构建 Compiler 线程, 已经经过去重
        // 构建 Iframe
        const iframe = new IframeEnv();
        this.iframe = iframe;

        return this.fileStore.getFileString("/index.html").then(() => {
            return iframe.mount({
                port,
                container: this.container,
                getFile: (src: string) => {
                    return this.fileStore.getFileString(src);
                },
                src: "/index.html",

                // 构建虚拟 URL
                root: new URL("/index.html", location.href).toString(),
            });
        });
    }
    async reload() {
        this.iframe?.destroy();
        this.build();
    }
    async destroy() {
        this.iframe?.destroy();
        super.destroy();
    }
}
